package com.minis.web.context;

import com.minis.web.context.support.AnnotationConfigWebApplicationContext;
import com.minis.web.context.support.XmlWebApplicationContext;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletContextEvent;
import jakarta.servlet.ServletContextListener;

public class ContextLoaderListener implements ServletContextListener {
    // IoC 容器的配置文件
    public static final String CONFIG_LOCATION_PARAM = "contextConfigLocation";
    private WebApplicationContext context;

    public ContextLoaderListener(WebApplicationContext context) {
        this.context = context;
    }

    public ContextLoaderListener() {
    }

    @Override
    public void contextInitialized(ServletContextEvent event) {
        initWebApplicationContext(event.getServletContext());
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
    }

    private void initWebApplicationContext(ServletContext servletContext) {
        String sContextLocation = servletContext.getInitParameter(CONFIG_LOCATION_PARAM);
        // 通过配置文件创建上下文
        WebApplicationContext wac = new XmlWebApplicationContext(sContextLocation);
        // 通过 servletContext 来设置新的上下文
        wac.setServletContext(servletContext);
        this.context = wac;
        // 将新的上下文添加到 servletContext 中，这样就能互相引用了
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
    }
}
